from datetime import datetime
import backtrader as bt
import pandas as pd
from data_feed import StockDataFetcher, MyStockData, etf_daily
from MyStrategy import Gain10, BacktestConfig, add_analyzer

symbol="000638"
adjust = "qfq"
start_date = datetime(2023, 1, 1)
end_date = datetime.now()

percentage=1.1
stop_loss=0.95
add_strategy=Gain10 #涨停策略
start_cash=50000
commission=0.002
slippage=0.00 #打涨停去掉滑点
directory_path=r'backtrader/利弗莫尔涨停战法'

# =============create a "Cerebro" engine instance==========
cerebro = bt.Cerebro()  
cerebro.broker.set_coc (True) # 设置以当日收盘价成交,coc代表cheat_on_close，
#set_coc (True) 那么在策略 def log(self, txt, dt=None): 中，日期就不是第二天成交，改成前一天self.datetime.date(-1)  
# =============添加etf数据源  ===================================
data_fetcher = StockDataFetcher(symbol=symbol,adjust=adjust) # 抓取股票行情类实例化
data_stock = data_fetcher.get_data()          # 对象的获取数据方法
data = MyStockData(dataname=data_stock, fromdate=start_date, todate=end_date) # 实例数据源 
cerebro.adddata(data, name=symbol)  # Add the data feed
# ==============添加策略========================================
cerebro.addstrategy(add_strategy, percentage=percentage, stop_loss=stop_loss)  # Add the trading strategy, 设置均线参数

# ==============置投资金额,佣金,============================
config = BacktestConfig(start_cash=start_cash, commission=commission, slippage=slippage)   #建立类(设置投资金额,佣金,分析及打印分析结果)
config.configure_broker(cerebro)       #设置投资金额,佣金,
# =================分析及打印分析结果===============
Analyzers=add_analyzer(start_cash=start_cash, directory_path=directory_path)
Analyzers.add_analyzers(cerebro)

results = cerebro.run()  # run it all

Analyzers.print_results(cerebro, results, start_date, end_date) # 打印分析结果
Analyzers.excel_results(cerebro, results, start_date, end_date,directory_path) # 买卖与分析输出到excel
#=====================================================================================

cerebro.plot()  # and plot it with a single command
